package com.young.dubbo.protocol.http;


import com.young.dubbo.framework.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http 客户端，用于发送调用接口，以及方法信息到远程服务，由远程服务处理后返回结果
 */
public class HttpClient {

    /**
     * 发送请求，并接受请求结果
     * @param hostname
     * @param port
     * @param invocation
     * @return
     */
    public String send(String hostname, int port, Invocation invocation){
        ObjectOutputStream oos=null;
        InputStream inputStream = null;
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http", hostname, port, "/").openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();

            oos = new ObjectOutputStream(outputStream);
            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            inputStream = httpURLConnection.getInputStream();
            String result = IOUtils.toString(inputStream);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                inputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
